﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using MINERP.DAL;
using MINERP.MODEL.FoundationModel;
using MINERP.MODEL.Frontier;
using MINERP.COM;
using MINERP.BLL.Common;
using System.Windows.Forms;

namespace MINERP.BLL.Frontier
{
    public class PrintBLL
    {
        public delegate void PrintTicketHander(MINERP.MODEL.Frontier.OrderInfo_Info orderInfo);
        public delegate void ShowErrMsgHander(string msg);
        public PrintTicketHander printTicketHander;
        public ShowErrMsgHander showErrMsgHander;
        WorkFlowListBLL workFlowListBLL = new WorkFlowListBLL();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderProductIdList"></param>
        /// <param name="printerInfo"></param>
        /// <returns>0,发送成功，1，复制照片出错，2，在热文件夹中创建orderFile文件夹出错,3 复制condition文件出错,4 创建end.txt失败,5 当前产品纸型或纸宽与打印纸不匹配,6 没有找到能发送的产品</returns>
        public int SendPhotoManage(List<int> orderProductIdList, Printer_Info printerInfo, int curTech, int userId, PrinterConfigInfo printerConfigInfo)
        {
            bool IsSomeOrderFileSendOK = false;
            int ret = 0;
            if (orderProductIdList.Count == 0)
            {
                ret = 6;
                return ret;
            }
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {

                foreach (var orderproductId in orderProductIdList)//产品
                {
                    MINERP.MODEL.Frontier.OrderInfo_Info orderInfo = GetOrderInfoToPrintTicket(orderproductId);
                    List<OrderFile> orderFileList = enty.OrderFile.Where(o => o.orderInfo.OrderProductId == orderproductId).ToList();
                    foreach (var orderfile in orderFileList)//文件夹
                    {
                        if (orderfile.Status != (int)OrderFileStatus.Created)
                            continue;
                        if (!orderfile.paperTypeReference.IsLoaded)
                        {
                            orderfile.paperTypeReference.Load();
                        }
                        //if (!orderfile.paperFaceReference.IsLoaded)
                        //{
                        //    orderfile.paperFaceReference.Load();
                        //}
                        PaperBox paperBox = enty.PaperBox.FirstOrDefault(p => p.PaperTypeName == orderfile.paperType.Name && p.PaperWidth == orderfile.Width && p.printer.PrinterID == printerInfo.PrinterID || p.PaperWidth == orderfile.Length && p.printer.PrinterID == printerInfo.PrinterID && p.PaperTypeName == orderfile.paperType.Name);
                        if (paperBox != null)//当前产品纸型或纸宽与打印纸不匹配
                        {
                            string path = printerInfo.HotDirPath + "\\" + orderfile.FolderName;
                            ret = CreateFolder(path);
                            if (ret == 0)
                            {
                                ret = CopyConditionFile(orderfile.ConditionFilePath, path + "\\condition.txt");
                                if (ret == 0)
                                {
                                    if (!orderfile.photoInfo.IsLoaded)
                                    {
                                        orderfile.photoInfo.Load();
                                    }
                                    bool allPhotoCopied = true; //文件夹内所有照片都复制完成
                                    if (orderfile.photoInfo.Count == 0)
                                    {
                                        ret = 1;
                                        showErrMsgHander.Invoke("产品号" + orderproductId + "找不到照片");
                                        try
                                        {
                                            Directory.Delete(path, true);
                                        }
                                        catch
                                        {

                                        }
                                        allPhotoCopied = false;
                                    }
                                    foreach (var photo in orderfile.photoInfo)//照片
                                    {
                                        try
                                        {
                                            FileInfo fi = new FileInfo(photo.picPath);
                                            File.Copy(photo.picPath, path + "\\" + fi.Name, true);
                                            photo.status = (int)PhotoStatus.Printed;
                                            enty.SaveChanges();
                                        }
                                        catch
                                        {
                                            ret = 1;//复制照片出错
                                            try
                                            {
                                                Directory.Delete(path, true);
                                            }
                                            catch
                                            {
                                            }
                                            allPhotoCopied = false;
                                            showErrMsgHander.Invoke("产品号" + orderproductId + "找不到照片：" + photo.picPath);

                                        }
                                    }
                                    if (allPhotoCopied)
                                    {
                                        try
                                        {
                                            if (!File.Exists(Application.StartupPath + "\\end.txt"))
                                            {
                                                FileStream fs = null;
                                                try
                                                {
                                                    fs = File.Create(Application.StartupPath + "\\end.txt");
                                                }
                                                finally
                                                {
                                                    fs.Close();
                                                }

                                            }
                                            File.Copy(Application.StartupPath + "\\end.txt", path + "\\end.txt", true);
                                            orderfile.Status = (int)OrderFileStatus.Printed;
                                            orderfile.lastPrintTime = DateTime.Now;
                                            enty.SaveChanges();
                                            IsSomeOrderFileSendOK = true;

                                        }
                                        catch (Exception ex)
                                        {
                                            ret = 4;
                                            showErrMsgHander.Invoke("产品号" + orderproductId + "创建 end.txt文件出错：" + ex.Message);
                                        }

                                    }
                                }
                                else
                                {
                                    orderfile.Status = (int)OrderFileStatus.Corrented;//condition找不到就将orderfile状态置为已修正状态，重新生成Condition文件
                                    if (!orderfile.photoInfo.IsLoaded)
                                    {
                                        orderfile.photoInfo.Load();
                                    }
                                    foreach (var item in orderfile.photoInfo)
                                    {
                                        item.status = (int)PhotoStatus.DistributedPrinter;
                                    }
                                    enty.SaveChanges();
                                    ret = 3;
                                    try
                                    {
                                        Directory.Delete(path, true);
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                            else
                            {
                                ret = 2;
                            }
                        }
                        else
                        {
                            ret = 5;
                        }
                    }

                    if (IsOrderProductComplete(orderproductId))
                    {
                        if (printerConfigInfo.IsAutoPrintTikect)//如果设置自动打印小票
                        {

                            printTicketHander.Invoke(orderInfo);
                            bool result = workFlowListBLL.OverCurTech(curTech, userId, orderproductId);

                        }
                        else
                        {
                            if (DialogResult.OK == MessageBox.Show("该产品已经完成要打印小票吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                            {
                                printTicketHander.Invoke(orderInfo);
                                
                            }
                            bool result = workFlowListBLL.OverCurTech(curTech, userId, orderproductId);
                        }

                    }
                }
            }
            if (IsSomeOrderFileSendOK)
            {
                ret = 0;
            }
            return ret;
        }

        /// <summary>
        /// phj2010-11-19号重载
        /// </summary>
        /// <param name="orderProductIdList"></param>
        /// <param name="printerInfo"></param>
        /// <returns>0,发送成功，1，复制照片出错，2，在热文件夹中创建orderFile文件夹出错,3 复制condition文件出错,4 创建end.txt失败,5 当前产品纸型或纸宽与打印纸不匹配,6 没有找到能发送的产品</returns>
        public int SendPhotoManage(List<int> orderProductIdList, Printer_Info printerInfo, int curTech, int userId, PrinterConfigInfo printerConfigInfo, int maxCount)
        {
            bool IsSomeOrderFileSendOK = false;
            int ret = 0;
            if (orderProductIdList.Count == 0)
            {
                ret = 6;
                return ret;
            }
            int hadMovedOrderCount = 0;//已经发送的定单数
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {

                foreach (var orderproductId in orderProductIdList)//产品
                {
                    MINERP.MODEL.Frontier.OrderInfo_Info orderInfo = GetOrderInfoToPrintTicket(orderproductId);
                    List<OrderFile> orderFileList = enty.OrderFile.Where(o => o.orderInfo.OrderProductId == orderproductId).ToList();
                    foreach (var orderfile in orderFileList)//文件夹
                    {
                        if (orderfile.Status != (int)OrderFileStatus.Created)
                            continue;
                        if (!orderfile.paperTypeReference.IsLoaded)
                        {
                            orderfile.paperTypeReference.Load();
                        }
                        //if (!orderfile.paperFaceReference.IsLoaded)
                        //{
                        //    orderfile.paperFaceReference.Load();
                        //}
                        PaperBox paperBox = enty.PaperBox.FirstOrDefault(p => p.PaperTypeName == orderfile.paperType.Name && p.PaperWidth == orderfile.Width && p.printer.PrinterID == printerInfo.PrinterID || p.PaperWidth == orderfile.Length && p.printer.PrinterID == printerInfo.PrinterID && p.PaperTypeName == orderfile.paperType.Name);
                        if (paperBox != null)//当前产品纸型或纸宽与打印纸不匹配
                        {
                            if (hadMovedOrderCount + 1 > maxCount)
                                break;

                            hadMovedOrderCount++;
                            string path = printerInfo.HotDirPath + "\\" + orderfile.FolderName;
                            ret = CreateFolder(path);
                            if (ret == 0)
                            {
                                ret = CopyConditionFile(orderfile.ConditionFilePath, path + "\\condition.txt");
                                if (ret == 0)
                                {
                                    if (!orderfile.photoInfo.IsLoaded)
                                    {
                                        orderfile.photoInfo.Load();
                                    }
                                    bool allPhotoCopied = true; //文件夹内所有照片都复制完成
                                    if (orderfile.photoInfo.Count == 0)
                                    {
                                        ret = 1;
                                        showErrMsgHander.Invoke("产品号" + orderproductId + "找不到照片");
                                        try
                                        {
                                            Directory.Delete(path, true);
                                        }
                                        catch
                                        {

                                        }
                                        allPhotoCopied = false;
                                    }
                                    foreach (var photo in orderfile.photoInfo)//照片
                                    {
                                        try
                                        {
                                            FileInfo fi = new FileInfo(photo.picPath);
                                            File.Copy(photo.picPath, path + "\\" + fi.Name, true);
                                            photo.status = (int)PhotoStatus.Printed;
                                            enty.SaveChanges();
                                        }
                                        catch
                                        {
                                            ret = 1;//复制照片出错
                                            try
                                            {
                                                Directory.Delete(path, true);
                                            }
                                            catch
                                            {
                                            }
                                            allPhotoCopied = false;
                                            showErrMsgHander.Invoke("产品号" + orderproductId + "找不到照片：" + photo.picPath);

                                        }
                                    }
                                    if (allPhotoCopied)
                                    {
                                        try
                                        {
                                            if (!File.Exists(Application.StartupPath + "\\end.txt"))
                                            {
                                                FileStream fs = null;
                                                try
                                                {
                                                    fs = File.Create(Application.StartupPath + "\\end.txt");
                                                }
                                                finally
                                                {
                                                    fs.Close();
                                                }

                                            }
                                            File.Copy(Application.StartupPath + "\\end.txt", path + "\\end.txt", true);
                                            orderfile.Status = (int)OrderFileStatus.Printed;
                                            orderfile.lastPrintTime = DateTime.Now;
                                            enty.SaveChanges();
                                            IsSomeOrderFileSendOK = true;

                                        }
                                        catch (Exception ex)
                                        {
                                            ret = 4;
                                            showErrMsgHander.Invoke("产品号" + orderproductId + "创建 end.txt文件出错：" + ex.Message);
                                        }

                                    }
                                }
                                else
                                {
                                    orderfile.Status = (int)OrderFileStatus.Corrented;//condition找不到就将orderfile状态置为已修正状态，重新生成Condition文件
                                    if (!orderfile.photoInfo.IsLoaded)
                                    {
                                        orderfile.photoInfo.Load();
                                    }
                                    foreach (var item in orderfile.photoInfo)
                                    {
                                        item.status = (int)PhotoStatus.DistributedPrinter;
                                    }
                                    enty.SaveChanges();
                                    ret = 3;
                                    try
                                    {
                                        Directory.Delete(path, true);
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                            else
                            {
                                ret = 2;
                            }
                        }
                        else
                        {
                            ret = 5;
                        }
                    }

                    if (IsOrderProductComplete(orderproductId))
                    {
                        if (printerConfigInfo.IsAutoPrintTikect)//如果设置自动打印小票
                        {

                            printTicketHander.Invoke(orderInfo);
                            bool result = workFlowListBLL.OverCurTech(curTech, userId, orderproductId);

                        }
                        else
                        {
                            if (DialogResult.OK == MessageBox.Show("该产品已经完成要打印小票吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                            {
                                printTicketHander.Invoke(orderInfo);
                                
                            }
                            bool result = workFlowListBLL.OverCurTech(curTech, userId, orderproductId);
                        }

                    }
                }
            }
            if (IsSomeOrderFileSendOK)
            {
                ret = 0;
            }
            return ret;
        }

        /// <summary>
        /// 判断产品是否打印完成
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        private bool IsOrderProductComplete(int orderProductId)
        {
            bool flag = true;
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {
                //现在修改为判断照片的状态是否都已打印，如果是才表示完成
                //List<OrderFile> list = enty.OrderFile.Where(o => o.orderInfo.OrderProductId == orderProductId).ToList();
                //foreach (var item in list)
                //{
                //    if (item.Status != (int)OrderFileStatus.Printed)
                //    {
                //        flag = false;
                //    }
                //}
               int photoPrintedStatus=(int) PhotoStatus.Printed;
               int photoFeiPianStatus = (int)PhotoStatus.FenPian;

               return enty.photoInfo.Count(p => p.orderInfo.OrderProductId == orderProductId && (p.status != photoPrintedStatus && p.status != photoFeiPianStatus)) <= 0;
            }
            return flag;
        }
        /// <summary>
        /// 得到orderInfo
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public MINERP.MODEL.Frontier.OrderInfo_Info GetOrderInfoToPrintTicket(int orderProductId)
        {
            MINERP.MODEL.Frontier.OrderInfo_Info oi = new MINERP.MODEL.Frontier.OrderInfo_Info();
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {
                MINERP.MODEL.Frontier.OrderInfo_Info orderInfo_info = new MINERP.MODEL.Frontier.OrderInfo_Info();
                List<PhotoInfo_Info> listPhoto = new List<PhotoInfo_Info>();

                orderInfo orderinfo = enty.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);

                OrderFile orderFile =enty.OrderFile.FirstOrDefault(o=>o.orderInfo.OrderProductId ==orderProductId);
                if(!orderFile.paperTypeReference.IsLoaded)
                {
                    orderFile.paperTypeReference.Load();
                }
                if (!orderinfo.photoInfo.IsLoaded)
                {
                    orderinfo.photoInfo.Load();
                }
                if (!orderinfo.Tb_ProductReference.IsLoaded)
                {
                    orderinfo.Tb_ProductReference.Load();
                }
                if(!orderinfo.OrderFile.IsLoaded)
                {
                    orderinfo.OrderFile.Load();
                }
                foreach (var item in orderinfo.photoInfo.ToList())
                {
                    if (item.status2 == 2)//如果是返单的一张就一张的出
                    {
                        PhotoInfo_Info photoInfo_info = new PhotoInfo_Info();
                        photoInfo_info.Height = item.Height;
                        photoInfo_info.Width = item.Width;
                        listPhoto.Add(photoInfo_info);
                    }
                    else
                    {
                        for (int i = 0; i < item.TotalNum * orderinfo.productNum; i++)
                        {
                            PhotoInfo_Info photoInfo_info = new PhotoInfo_Info();
                            photoInfo_info.Height = item.Height;
                            photoInfo_info.Width = item.Width;
                            listPhoto.Add(photoInfo_info);
                        }
                    }
                }
                oi.OrderProductId = orderinfo.OrderProductId;
                oi.OrderProductName = orderinfo.OrderProductName;
                oi.CtmName = orderinfo.CtmName;
                oi.Priority = (int)orderinfo.Priority;
                oi.Remark = orderinfo.Remark;
                oi.PhotoInfoList = listPhoto;
                oi.ProductDes = orderinfo.Tb_Product.ProductDes;
                oi.PaperTypeName = orderFile.paperType.Name;
            }
            return oi;
        }
        /// <summary>
        /// 创建orderFile文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private int CreateFolder(string path)
        {
            int ret = 0;
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                ret = -1;
            }
            return ret;
        }
        /// <summary>
        /// 复制Condition 文件
        /// </summary>
        /// <param name="spath"></param>
        /// <param name="dpath"></param>
        /// <returns></returns>
        private int CopyConditionFile(string spath, string dpath)
        {
            int ret = 0;

            try
            {

                File.Copy(spath, dpath, true);

            }
            catch (Exception ex)
            {
                WriteLogForCheck.WriteLogFile(DateTime.Now + "  复制condition出错" + ex.Message);
                if (ex is FileNotFoundException)
                {
                    ret = 1;
                }
            }
            return ret;
        }

        /// <summary>
        /// 重新生成
        /// </summary>
        /// <param name="listProductId"></param>
        /// <returns></returns>
        public int OrderFileRebuild(List<int> listProductId)
        {
            int ret = 0;
            try
            {
                using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
                {
                    foreach (var orderproductId in listProductId)//产品
                    {
                        List<OrderFile> orderFileList = enty.OrderFile.Where(o => o.orderInfo.OrderProductId == orderproductId).ToList();
                        foreach (var item in orderFileList)
                        {
                            if (!item.photoInfo.IsLoaded)
                            {
                                item.photoInfo.Load();
                            }
                            foreach (var photo in item.photoInfo)
                            {
                                photo.status = (int)PhotoStatus.DistributedPrinter;
                            }

                            item.Status = (int)OrderFileStatus.Corrented;
                        }
                    }
                    enty.SaveChanges();
                }

            }
            catch
            {
                ret = 1;
            }

            return ret;
        }

        /// <summary>
        /// 重新打印
        /// </summary>
        /// <param name="listProductId"></param>
        /// <returns></returns>
        public int OrderFileRePrint(List<int> listProductId)
        {
            int ret = 0;
            try
            {
                using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
                {
                    foreach (var orderproductId in listProductId)//产品
                    {
                        List<OrderFile> orderFileList = enty.OrderFile.Where(o => o.orderInfo.OrderProductId == orderproductId).ToList();
                        foreach (var item in orderFileList)
                        {
                            if (item.Status == (int)OrderFileStatus.Printed)
                            {
                                item.Status = (int)OrderFileStatus.Created;
                                enty.SaveChanges();
                            }
                        }

                    }
                }
            }
            catch
            {
                ret = 1;
            }
            return ret;

        }


        public int OrderFilePriority(List<int> listProductId, int priority)
        {
            int ret = 0;
            try
            {
                using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
                {
                    foreach (var orderproductId in listProductId)//产品
                    {
                        List<OrderFile> orderFileList = enty.OrderFile.Where(o => o.orderInfo.OrderProductId == orderproductId).ToList();
                        //orderInfo oi = enty.orderInfo.FirstOrDefault(o=>o.OrderProductId==orderproductId);
                        //oi.Priority = priority;
                        foreach (var item in orderFileList)
                        {
                            item.Priority = priority;
                        }

                        enty.SaveChanges();

                    }
                }
            }
            catch 
            {
                ret = 1;
            }
            return ret;

        }
    }
}
